#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int, int>;
#define rep(i, a, b) for (int i = (a); i <= (b); i++)
#define per(i, a, b) for (int i = (a); i >= (b); i--)
#define endl '\n'
const int N = 5005;

int n, m;
int a[N], b[N], num;
ll dp[2][N];
void solve() {
  cin >> n;
  rep(i, 1, n) cin >> a[i];
  rep(i, 1, n) b[i] = a[i];
  sort(b + 1, b + n + 1);
  num = unique(b + 1, b + n + 1) - b - 1;
  rep(i, 1, n) {
    int now = i & 1;
    int pre = now ^ 1;
    ll mn = 1e18;
    rep(j, 1, num) {
      mn = min(mn, dp[pre][j]);
      dp[now][j] = mn + abs(a[i] - b[j]);
    }
  }
  ll ans = 1e18;
  rep(j, 1, num) ans = min(ans, dp[n & 1][j]);
  cout << ans;
  return;
}
int main() {
  ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  int t = 1;
  while (t--) solve();
  return 0;
}